﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using ITM495.Lab2.Core;
using ITM495.Lab2.Core.Entities;
using System.Xml;
using System.Xml.Linq;

namespace ITM495.Lab2.Impl.Writers
{
    public class XmlWriter : IWriter<Tweet>
    {
        protected String Path { get; set; }

        protected XmlDocument tweetDoc;

        public XmlWriter(string path)
        {
            Path = path;

            tweetDoc = new XmlDocument();
        }

        #region IWriter<Tweet> Members

        public void Write(IList<Tweet> entities)
        {
            using(var tweetWriter = new XmlTextWriter(Path, Encoding.UTF8))
            {
                tweetWriter.WriteStartElement("rss");
                tweetWriter.WriteStartElement("channel");
                
                foreach (var t in entities)
                {
                    tweetWriter.WriteStartElement("item");

                    WriteElement(tweetWriter, "title", t.Title);
                    WriteElement(tweetWriter, "description", t.Description);
                    WriteElement(tweetWriter, "pubDate", t.PubDate.ToString("d"));
                    WriteElement(tweetWriter, "guid", t.Guid);
                    WriteElement(tweetWriter, "link", t.Link);

                    tweetWriter.WriteEndElement();
                }

                tweetWriter.WriteEndElement();
                tweetWriter.WriteEndElement();
            }
        }

        #endregion

        public void WriteElement(XmlTextWriter writer, string name, string value)
        {
            writer.WriteStartElement(name);
            writer.WriteString(value);
            writer.WriteEndElement();
        }
    }
}
